//
//  HomeViewController.m
//  WXWeibo
//
//  Created by apple on 16/5/9.
//  Copyright © 2016年 zic_magic. All rights reserved.
//

#import "HomeViewController.h"
#import "SinaWeibo.h"
#import "AppDelegate.h"
#import "ThemeManager.h"
#import "ThemeLabel.h"
#import "WeiboModel.h"
#import "YYModel.h"
#import "WeiboCellLayout.h"
#import "WXRefresh.h"
#import "ThemeImageView.h"
#import <AVFoundation/AVFoundation.h>
@interface HomeViewController () <SinaWeiboDelegate,SinaWeiboRequestDelegate>
@property (nonatomic, strong)NSMutableArray *weiboList;
@property (nonatomic, strong)ThemeImageView *notifyImgview;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"Home";
    
    [_weiboTableView addPullDownRefreshBlock:^{
        
        [self _loadNewWeiboData];
        
    }];
    [_weiboTableView addInfiniteScrollingWithActionHandler:^{
        
        [self _loadNextPageWeiboData];
        
    }];
    
    
    
    SinaWeibo *sinaWeibo = [self sinaWeibo];
    sinaWeibo.delegate = self;
    
    if (![sinaWeibo isAuthValid]) {
        
        [sinaWeibo logIn];
    
    }else {
        
        NSDictionary *params = @{
                                 @"count" : @"10"
                                 };
        
       SinaWeiboRequest *request = [sinaWeibo requestWithURL:@"statuses/home_timeline.json" params:[params mutableCopy] httpMethod:@"GET" delegate:self];
        request.weiboTag = WeiboRequestNormal;
    }


    
}

- (void)_loadNewWeiboData {
    
    WeiboCellLayout *newLayout = [self.weiboList firstObject];
    NSString *sinceID = newLayout.weibo.idstr;
    
    NSDictionary *params = @{
                             @"since_id" : sinceID
                             };
    
    SinaWeiboRequest *request = [[self sinaWeibo] requestWithURL:@"statuses/home_timeline.json" params:[params mutableCopy] httpMethod:@"GET" delegate:self];
    
    request.weiboTag = WeiboRequestNew;
}


- (void)_loadNextPageWeiboData{
    
    //取得当前显示的最后一条微博的 id
    WeiboCellLayout *layout = [self.weiboList lastObject];
    NSString *weibID = layout.weibo.idstr;
    
    SinaWeiboRequest *request = [[self sinaWeibo] requestWithURL:@"statuses/home_timeline.json"params:[@{@"max_id" : weibID} mutableCopy] httpMethod:@"GET" delegate:self];
    
    request.weiboTag = WeiboRequestNextPage;
    
}
- (NSMutableArray *)weiboList {
    
    if (_weiboList == nil) {
        _weiboList = [NSMutableArray array];
    }
    return _weiboList;
}

- (ThemeImageView *)notifyImgview {
    if (_notifyImgview == nil) {
        _notifyImgview = [[ThemeImageView alloc] initWithFrame:CGRectMake(10, -40, kScreenWidth -20, 40)];
        _notifyImgview.imgName = @"timeline_notify";
        
        [self.view addSubview:_notifyImgview];
        
        ThemeLabel *label = [[ThemeLabel alloc] initWithFrame:_notifyImgview.bounds];
        
        label.colorName = @"Mask_Notice_color";
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 1000;
        [_notifyImgview addSubview:label];
    }
    return _notifyImgview;
    
}
- (SinaWeibo *)sinaWeibo {
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo {
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token",
                              nil
                              ];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
}

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error {
    
//    NSLog(@"%@", error);
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    
    NSArray *statuses = result[@"statuses"];
    
    NSMutableArray *tempArr = [NSMutableArray array];
    
    for (NSDictionary *dic in statuses) {
        
        WeiboModel *weibo = [WeiboModel yy_modelWithDictionary:dic];
        WeiboCellLayout *weiboLayout = [[WeiboCellLayout alloc] init];
        weiboLayout.weibo = weibo;
        
        
        [tempArr addObject:weiboLayout];
        

    }
    
    if (request.weiboTag == WeiboRequestNormal) {
        
        self.weiboList = tempArr;
        
    }
    else if (request.weiboTag == WeiboRequestNew) {
        
        
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, tempArr.count)];
        
        [self.weiboList insertObjects:tempArr atIndexes:set];
        

        [self.weiboTableView.pullToRefreshView stopAnimating];
        
    } else if (request.weiboTag == WeiboRequestNextPage) {
        
        WeiboCellLayout *fistLayout = [tempArr firstObject];
        WeiboCellLayout *lastLayout = [self.weiboList lastObject];
        if ([fistLayout.weibo.idstr isEqualToString:lastLayout.weibo.idstr]) {
            [tempArr removeObjectAtIndex:0];
        }
        
        
        [self.weiboList addObjectsFromArray:tempArr];
        
    
        [self.weiboTableView.infiniteScrollingView stopAnimating];
        
    }

    
    self.weiboTableView.weiboList = self.weiboList;

    [self.weiboTableView reloadData];
    
}

#pragma mark- 未读微博

- (void)showNofifyView:(NSInteger)count {
    
    if (count <= 0) {
        return;
    }
    
    ThemeLabel *label = (ThemeLabel *)[self.notifyImgview viewWithTag:1000];
    label.text = [NSString stringWithFormat:@"%ld 条新微博", count];
    [UIView animateWithDuration:0.25 animations:^{
        self.notifyImgview.transform = CGAffineTransformMakeTranslation(0, 50);
    }completion:^(BOOL finished) {
        [UIView animateKeyframesWithDuration:0.3 delay:1.5 options:UIViewKeyframeAnimationOptionLayoutSubviews animations:^{
            self.notifyImgview.transform = CGAffineTransformIdentity;
        } completion:NULL];
    }];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"msgcome.wav" ofType:nil];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    SystemSoundID soundID = 0;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(fileURL), &soundID);
    
    AudioServicesPlaySystemSound(soundID);
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.weiboTableView reloadData];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
